﻿// ***********************************************************************
// Assembly         : INNOVACALL.Framework.Common
// Author           : LJO+01 (Laurent Jordi)
// Created          : 06-05-2013
// Last Modified By : LJO+01 (Laurent Jordi)
// Last Modified On : 06-05-2013
// ***********************************************************************
// <copyright file="StringsExtensions.cs" company="Copyright © Innovacall 2011">
//     Copyright (c) Copyright © Innovacall 2011. All rights reserved.
// </copyright>
// <summary></summary>
// ***********************************************************************
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Xml;
using System.Xml.Serialization;
using INNOVACALL.Framework.Common.Properties;

namespace INNOVACALL.Framework.Common.Extensions
{
    /// <summary>
    /// All extensions for strings
    /// </summary>
	public static class StringExtension
	{
		/// <summary>
		/// Read entire file content en return it in a byte[]
		/// </summary>
		/// <param name="fileName">Just the filename</param>
		/// <param name="filePath">Path to file</param>
		/// <returns></returns>
		public static byte[] GetFileData(this string fileName, string filePath)
		{
			var fullFilePath = Path.Combine(filePath, fileName);
			if (!File.Exists(fullFilePath))
				throw new FileNotFoundException(Resources.ErrMsg_Extensions_Strings_GetFileData_FileNotFound, fullFilePath);
			return File.ReadAllBytes(fullFilePath);
		}
		/// <summary>
		/// Deserializes the specified xmlstring.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="xmlstring">The xmlstring.</param>
		/// <returns></returns>
		public static T Deserialize<T>(this string xmlstring) where T : class
		{
			XmlSerializer aXml = new XmlSerializer(typeof(T), "");
			MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(xmlstring));
			XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
			return aXml.Deserialize(memoryStream) as T;
		}

		/// <summary>
		/// Strings to UT f8 byte array.
		/// </summary>
		/// <param name="pXmlString">The p XML string.</param>
		/// <returns></returns>
		public static Byte[] StringToUTF8ByteArray(this String pXmlString)
		{
			UTF8Encoding encoding = new UTF8Encoding();
			Byte[] byteArray = encoding.GetBytes(pXmlString);
			return byteArray;
		}

		/// <summary>
		/// Encodes the SH a1.
		/// </summary>
		/// <param name="text">The text.</param>
		/// <returns></returns>
		public static string EncodeSHA1(this string text)
		{
			System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();

			byte[] buffer = enc.GetBytes(text);
			SHA1CryptoServiceProvider cryptoTransformSHA1 =
			new SHA1CryptoServiceProvider();
			string hash = BitConverter.ToString(cryptoTransformSHA1.ComputeHash(buffer)).Replace("-", "");
			return hash;
		}

		/// <summary>
		/// Encodes the MD5.
		/// </summary>
		/// <param name="input">The input.</param>
		/// <returns></returns>
		public static string EncodeMd5(this string input)
		{
			MD5 md5Hasher = MD5.Create();

			byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));

			StringBuilder sBuilder = new StringBuilder();

			for (int i = 0; i < data.Length; i++)
			{
				sBuilder.Append(data[i].ToString("x2"));
			}
			return sBuilder.ToString();
		}

		public static string TrimAL(this string input)
		{
			if (string.IsNullOrEmpty(input)) 
				return string.Empty;

			string toReturn;
			toReturn = input.Trim();
			toReturn = (string.IsNullOrEmpty(toReturn) || string.IsNullOrWhiteSpace(toReturn) ? " " : toReturn);

			//toReturn = Regex.Replace(toReturn, "[^0-9a-zA-Z]+", "");
			return toReturn;
		}

		public static string UnMapPath(this string folder)
		{
			string tmp;
			string strRoot;
			strRoot = HttpContext.Current.Server.MapPath("/");
			tmp = folder.ToLower().Replace(strRoot.ToLower(), "");
			tmp = tmp.Replace(@"\", @"/");
			return tmp;
		}

		/// <summary>
		/// Remove HTML tags from string using char array.
		/// </summary>
		public static string    StripTagsCharArray(this string source)
		{
			char[] array = new char[source.Length];
			int arrayIndex = 0;
			bool inside = false;

			for (int i = 0; i < source.Length; i++)
			{
				char let = source[i];
				if (let == '<')
				{
					inside = true;
					continue;
				}
				if (let == '>')
				{
					inside = false;
					continue;
				}
				if (!inside)
				{
					array[arrayIndex] = let;
					arrayIndex++;
					if (source[i + 1] == '<')
					{
						array[arrayIndex] = ' ';
						arrayIndex++;
					}
				}
			}
			return new string(array, 0, arrayIndex);
		}
		/// <summary>
		/// Renvoyer le contenu d'un fichier passé en paramètre sous la forme d'une chaine de caractère
		/// </summary>
		/// <param name="fileName">Chemin complet du fichier</param>
		/// <returns>Contenu du fichier</returns>
		public static string ReadContentFile(this string fileName)
		{
			try
			{
				string content = default(string);
				using (FileStream file = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
				{
					using (var reader = new StreamReader(file))
					{
						content = reader.ReadToEnd();
					}
				}
				return content;
			}
			catch (Exception ex)
			{
				return string.Empty;
			}
		}

	}
}
